import { ref } from 'vue'
import { defineStore } from 'pinia'
import md5 from 'md5'
import { loginUser, getProfile, registerUser } from '../server/api/sys'
import { getStorage, setStorage, removeAllStorage } from '@/utils/storage'
import { TOKEN } from '@/assets/js/constant'

export const useUserStore = defineStore('user', () => {
  /**
   * state
   */
  const token = ref(getStorage(TOKEN) || '')
  const userInfo = ref({})

  /**
   * actions
   */
  // 登录
  async function login(payload) {
    const { password } = payload
    const data = await loginUser({
      ...payload,
      password: password ? md5(password) : ''
    })
    token.value = data.token
    setStorage(TOKEN, token.value)
  }

  // 获取用户信息
  async function profile() {
    const userProfile = await getProfile()
    userInfo.value = userProfile
  }

  // 退出登录
  function logout() {
    token.value = ''
    userInfo.value = {}
    removeAllStorage()
  }

  // 用户注册
  async function register(payload) {
    const { password } = payload
    return await registerUser({
      ...payload,
      password: password ? md5(password) : ''
    })
  }

  return {
    token,
    userInfo,
    login,
    profile,
    logout,
    register
  }
})
